iT邦幫忙

2024 iThome 鐵人賽

DAY 22
0

前言

前篇文章將官方範例的寫法寫上 Spring,接著我們要將 LightsPlugin 在 Spring 上呈現

LightModel

首先我們要建立一個 LightModel,這個Model會用來存放指定的Light的資訊,包括了id、name、isOn

image

接著輸入以下的程式碼,其實就是將需要的結構用一個 Class包裝

public class LightModel {
    private final int id;
    private final String name;
    private boolean isOn;

    public LightModel(int id, String name, boolean isOn) {
        this.id = id;
        this.name = name;
        this.isOn = isOn;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public boolean isOn() {
        return isOn;
    }

    public void setIsOn(boolean isOn) {
        this.isOn = isOn;
    }
}

LightsPlugin

接著是 Plugin 的部分,這裡就只要將官方的程式碼複製貼上,就大功告成囉~

public class LightsPlugin {

  // Mock data for the lights
  private final Map<Integer, LightModel> lights = new HashMap<>();

  public LightsPlugin() {
    lights.put(1, new LightModel(1, "Table Lamp", false));
    lights.put(2, new LightModel(2, "Porch light", false));
    lights.put(3, new LightModel(3, "Chandelier", true));
  }

  @DefineKernelFunction(name = "get_lights", description = "Gets a list of lights and their current state")
  public List<LightModel> getLights() {
    System.out.println("Getting lights");
    return new ArrayList<>(lights.values());
  }

  @DefineKernelFunction(name = "change_state", description = "Changes the state of the light")
  public LightModel changeState(
      @KernelFunctionParameter(name = "id", description = "The ID of the light to change") int id,
      @KernelFunctionParameter(name = "isOn", description = "The new state of the light") boolean isOn) {
    System.out.println("Changing light " + id + " " + isOn);
    if (!lights.containsKey(id)) {
      throw new IllegalArgumentException("Light not found");
    }

    lights.get(id).setIsOn(isOn);

    return lights.get(id);
  }
}

Kernel

這個部分要將剛剛建立的 plugin 加進來,這樣就可以讓 AI 辨識這個功能

        KernelPlugin lightPlugin = KernelPluginFactory.createFromObject(new LightPlugin(),
                "LightsPlugin");

        kernel = Kernel.builder()
                .withAIService(ChatCompletionService.class, chatCompletionService)
                .withPlugin(lightPlugin)
                .build();

        ContextVariableTypes
                .addGlobalConverter(
                        ContextVariableTypeConverter.builder(LightModel.class)
                                .toPromptString(new Gson()::toJson)
                                .build());

上一篇
[DAY21] 在 Spring 架設 Semantic Kernel
下一篇
[DAY23] 利用 AI 幫忙生成一個 Semantic Kernel 可以辨識的方法
系列文
智慧語義互動平台:基於Spring和Semantic Kernel的Android應用創新30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言